package com.mobialia.socialmediademo;

import java.util.ArrayList;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Toast;


public class LinkedInActivity extends ListActivity implements Runnable{
	
	public final static String TAG = "UpdateListActivity";
	
	public final static int MESSAGE_ERROR = 1;
	public final static int MESSAGE_UPDATE_LIST = 2;
	
	UpdateAdapter adapter;
	Thread thread;
	ProgressDialog loadingDialog;
	ArrayList<Update> updates;
	
	LinkedInProvider linkedInProvider;
	
	boolean running = true;
	
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (loadingDialog != null && loadingDialog.isShowing()) {
				loadingDialog.dismiss();
			}
			switch (msg.what) {
			case MESSAGE_ERROR:
				Toast.makeText(LinkedInActivity.this, R.string.error, Toast.LENGTH_SHORT).show();
				break;
			case MESSAGE_UPDATE_LIST:
				adapter.setUpdates(updates);
				adapter.notifyDataSetChanged();
			}
		}
	};
	
	public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
		// No Titlebar
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		requestWindowFeature(Window.FEATURE_PROGRESS);
 	    
	    setContentView(R.layout.linkedin);
        
        adapter = new UpdateAdapter(this);
		setListAdapter(adapter);
    }
	
	@Override
	protected void onResume() {
		super.onResume();
		
    	loadingDialog = ProgressDialog.show(this, "", getResources().getText(R.string.loading), true, true);
    	loadingDialog.show();
		thread = new Thread(this);
		thread.start();
		running = true;
		
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		running = false;
		handler.removeMessages(MESSAGE_ERROR);
		handler.removeMessages(MESSAGE_UPDATE_LIST);
	}
	
	public void onBackAction(View v) {
		finish();
	}
	
    public void onLogoutAction(View v) {
    	if (linkedInProvider != null) linkedInProvider.logout(this);
    	finish();
    }

	@Override
	public void run() {
		try {
			linkedInProvider = new LinkedInProvider(this);

			if (!linkedInProvider.isAuthenticated()) {
				linkedInProvider.launchAuth(this);
				finish();
			} else {
				updates = linkedInProvider.getUpdates();
				handler.sendEmptyMessage(MESSAGE_UPDATE_LIST);
			}
		} catch (Exception e) {
			e.printStackTrace();
			handler.sendEmptyMessage(MESSAGE_ERROR);
		}
	}
}